#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>

// ============== 宏定义 ==============
#define PORT         9080
#define BUF_SIZE     4096

// ============== 函数声明 ==============
void send_http_response(int fd, const char *content);

// ============== 主函数 ==============
int main() {
    // 创建socket
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd < 0) {
        perror("socket");
        return -1;
    }

    // 设置端口复用
    int reuse = 1;
    setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    // 绑定地址
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(PORT),
        .sin_addr.s_addr = INADDR_ANY
    };
    
    if (bind(socket_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind");
        close(socket_fd);
        return -1;
    }

    // 开始监听
    listen(socket_fd, 5);
    printf("Server started on port %d\n", PORT);

    // 接受客户端连接
    struct sockaddr_in client_addr;
    socklen_t addr_len = sizeof(client_addr);
    int client_fd = accept(socket_fd, (struct sockaddr*)&client_addr, &addr_len);
    if (client_fd < 0) {
        perror("accept");
        close(socket_fd);
        return -1;
    }

    printf("New connection from %s:%d\n", 
          inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

    // 主循环（监听stdin和客户端socket）
    fd_set read_fds;
    char buf[BUF_SIZE];

    while (1) {
        FD_ZERO(&read_fds);
        FD_SET(STDIN_FILENO, &read_fds);    // 监听标准输入
        FD_SET(client_fd, &read_fds);       // 监听客户端

        // 等待活动（无限期阻塞）
        if (select(client_fd + 1, &read_fds, NULL, NULL, NULL) < 0) {
            perror("select");
            break;
        }

        // 1. 处理stdin输入（服务端主动发消息）
        if (FD_ISSET(STDIN_FILENO, &read_fds)) {
            printf("Server input > ");
            fflush(stdout);

            if (fgets(buf, sizeof(buf), stdin) == NULL) break;
            
            // 封装为HTTP格式后发送
            char response[BUF_SIZE];
            snprintf(response, sizeof(response),
                    "HTTP/1.1 200 OK\r\n"
                    "Content-Type: text/plain\r\n"
                    "Content-Length: %zu\r\n\r\n"
                    "Server says: %s",
                    strlen(buf) + 13, buf);
            
            send(client_fd, response, strlen(response), 0);
        }

        // 2. 处理客户端消息
        if (FD_ISSET(client_fd, &read_fds)) {
            ssize_t len = recv(client_fd, buf, sizeof(buf), 0);
            if (len <= 0) {
                printf("Client disconnected\n");
                break;
            }

            printf("Received from client:\n%.*s\n", (int)len, buf);
            
            // 示例：自动回复（可删除或修改）
            send_http_response(client_fd, "{\"status\":\"received\"}");
        }
    }

    close(client_fd);
    close(socket_fd);
    return 0;
}

// ============== 函数实现 ==============
void send_http_response(int fd, const char *content) {
    char response[BUF_SIZE];
    snprintf(response, sizeof(response),
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: application/json\r\n"
            "Content-Length: %zu\r\n\r\n"
            "%s\r\n",
            strlen(content), content);
    
    send(fd, response, strlen(response), 0);
}

